function buildChildren(parent, all, parentKey, rowKey, labelField, valueField) {
  const _parents = []
  parent._parents.forEach((t) => {
    _parents.push(t)
  })
  _parents.push(parent[valueField || rowKey])
  all.forEach((item) => {
    if (parent[rowKey] == item[parentKey]) {
      if (!parent.children) {
        parent.children = []
      }
      let child = JSON.parse(JSON.stringify(item))
      child._parents = _parents
      buildChildren(child, all, parentKey, rowKey, labelField, valueField)
      parent.children.push(child)
    }
  })
}
function buildTree(data, parentKey, rowKey, labelField, valueField) {
  const res = []
  if (data) {
    data.forEach((item) => {
      if (!item[parentKey]) {
        let child = JSON.parse(JSON.stringify(item))
        child._parents = []
        res.push(child)
      }
    })
    res.forEach((item) => {
      buildChildren(item, data, parentKey, rowKey, labelField, valueField)
    })
  }
  return res
}
function findInTree(data, rowKey, val) {
  let res = null
  if (data && data.length > 0) {
    data.forEach((item) => {
      if (item[rowKey] == val) {
        res = item
      } else {
        if (!res) {
          res = findInTree(item.children, rowKey, val)
        }
      }
    })
  }
  return res
}
function findAllChildrenKeys(tree, rowKey, val) {
  const item = findInTree(tree, rowKey, val)
  const res = []
  if (item) {
    addChildrenKeys(item.children, res, rowKey)
  }
  return res
}
function addChildrenKeys(children, array, rowKey) {
  if (children) {
    children.forEach((item) => {
      array.push(item[rowKey])
      addChildrenKeys(item.children, array, rowKey)
    })
  }
}
export { buildTree, findInTree, findAllChildrenKeys }
